"use client"

import { useState } from "react"
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Search,
  Filter,
  Trash2,
  Plus,
  Calendar,
} from "lucide-react"
import Link from "next/link"
import { mockTickets } from "@/lib/data"
import { mockUsers } from "@/mocks/admin-data"
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import { Label } from "@/components/ui/label"

// Format date helper
const formatDate = (dateString: string | null) => {
  if (!dateString) return "N/A"
  const date = new Date(dateString)
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit"
  })
}

export default function TicketsHistoryPage() {
  const [tickets, setTickets] = useState(mockTickets)
  const [searchTerm, setSearchTerm] = useState("")
  const [statusFilter, setStatusFilter] = useState<string>("all")
  const [operatorFilter, setOperatorFilter] = useState<string>("all")
  const [startDate, setStartDate] = useState<string>("")
  const [endDate, setEndDate] = useState<string>("")
  const [showVoidAlert, setShowVoidAlert] = useState<string | null>(null)

  // Filter tickets logic
  const filteredTickets = tickets.filter(ticket => {
    const searchLower = searchTerm.toLowerCase()
    const matchesSearch =
      searchTerm === "" ||
      ticket.id.toLowerCase().includes(searchLower) ||
      ticket.target.toLowerCase().includes(searchLower) ||
      ticket.applicant.toLowerCase().includes(searchLower) ||
      ticket.operator.toLowerCase().includes(searchLower)

    const matchesStatus = statusFilter === "all" || ticket.status === statusFilter
    
    const matchesOperator =
      operatorFilter === "all" || ticket.operator === operatorFilter

    const ticketDate = new Date(ticket.applicationTime)
    
    // 处理日期筛选
    let matchesDate = true
    if (startDate) {
      const startDateTime = new Date(startDate)
      matchesDate = ticketDate >= startDateTime
    }
    if (endDate && matchesDate) {
      const endDateTime = new Date(endDate)
      matchesDate = ticketDate <= endDateTime
    }

    return matchesSearch && matchesStatus && matchesOperator && matchesDate
  })

  const handleVoidTicket = (ticketId: string) => {
    setTickets(currentTickets =>
      currentTickets.map(ticket =>
        ticket.id === ticketId ? { ...ticket, status: "已作废" } : ticket
      )
    )
    setShowVoidAlert(null)
  }

  const getStatusBadgeClass = (status: string) => {
    switch (status) {
      case "已完成":
        return "bg-green-100 text-green-800 border-green-300"
      case "进行中":
        return "bg-blue-100 text-blue-800 border-blue-300"
      case "待执行":
        return "bg-yellow-100 text-yellow-800 border-yellow-300"
      case "已作废":
        return "bg-red-100 text-red-800 border-red-300 line-through"
      default:
        return "bg-gray-100 text-gray-800 border-gray-300"
    }
  }

  return (
    <div className="space-y-6 p-4 md:p-10 pb-16">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">作业票历史查询</h2>
          <p className="text-muted-foreground">
            在这里查询、筛选和管理所有的历史作业票。
          </p>
        </div>
        <Link href="/tickets/create">
          <Button>
            <Plus className="mr-2 h-4 w-4" />
            新建作业票
          </Button>
        </Link>
      </div>

      <Card>
        <CardHeader>
          <div className="flex flex-col gap-4">
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
              <Input
                placeholder="搜索票号、目标、申请人..."
                value={searchTerm}
                onChange={e => setSearchTerm(e.target.value)}
                className="lg:col-span-2"
              />
              <Select
                value={operatorFilter}
                onValueChange={setOperatorFilter}
              >
                <SelectTrigger>
                  <SelectValue placeholder="所有操作员" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">所有操作员</SelectItem>
                  {mockUsers.map(user => (
                    <SelectItem key={user.id} value={user.name}>
                      {user.name}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
              <Select value={statusFilter} onValueChange={setStatusFilter}>
                <SelectTrigger>
                  <SelectValue placeholder="所有状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">所有状态</SelectItem>
                  <SelectItem value="待执行">待执行</SelectItem>
                  <SelectItem value="进行中">进行中</SelectItem>
                  <SelectItem value="已完成">已完成</SelectItem>
                  <SelectItem value="已作废">已作废</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label htmlFor="start-date" className="flex items-center">
                  <Calendar className="mr-2 h-4 w-4" />
                  开始日期时间
                </Label>
                <Input
                  id="start-date"
                  type="datetime-local"
                  value={startDate}
                  onChange={e => setStartDate(e.target.value)}
                  className="w-full"
                  step="1" // 精确到秒
                />
              </div>
              <div className="space-y-2">
                <Label htmlFor="end-date" className="flex items-center">
                  <Calendar className="mr-2 h-4 w-4" />
                  结束日期时间
                </Label>
                <Input
                  id="end-date"
                  type="datetime-local"
                  value={endDate}
                  onChange={e => setEndDate(e.target.value)}
                  className="w-full"
                  step="1" // 精确到秒
                />
              </div>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b">
                  <th className="px-4 py-3 text-left font-medium text-muted-foreground">
                    操作票号
                  </th>
                  <th className="px-4 py-3 text-left font-medium text-muted-foreground">
                    作业目标
                  </th>
                  <th className="px-4 py-3 text-left font-medium text-muted-foreground">
                    状态
                  </th>
                  <th className="px-4 py-3 text-left font-medium text-muted-foreground">
                    申请时间
                  </th>
                  <th className="px-4 py-3 text-left font-medium text-muted-foreground">
                    人员
                  </th>
                  <th className="px-4 py-3 text-center font-medium text-muted-foreground">
                    操作
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y">
                {filteredTickets.map(ticket => (
                  <tr key={ticket.id} className="hover:bg-muted/50">
                    <td className="px-4 py-3 font-medium">{ticket.id}</td>
                    <td className="px-4 py-3">{ticket.target}</td>
                    <td className="px-4 py-3">
                      <Badge
                        variant="outline"
                        className={getStatusBadgeClass(ticket.status)}
                      >
                        {ticket.status}
                      </Badge>
                    </td>
                    <td className="px-4 py-3 text-muted-foreground">
                      {formatDate(ticket.applicationTime)}
                    </td>
                    <td className="px-4 py-3">
                      <div>申请: {ticket.applicant}</div>
                      <div className="text-muted-foreground">
                        操作: {ticket.operator}
                      </div>
                    </td>
                    <td className="px-4 py-3 text-center">
                      <div className="flex items-center justify-center gap-2">
                        <Link href={`/tickets/${ticket.id}`}>
                          <Button variant="outline" size="sm">
                            查看
                          </Button>
                        </Link>
                        {ticket.status !== "已作废" && ticket.status !== '进行中' && (
                          <Button
                            variant="destructive"
                            size="sm"
                            onClick={() => setShowVoidAlert(ticket.id)}
                          >
                            <Trash2 className="mr-1 h-4 w-4" />
                            作废
                          </Button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
                {filteredTickets.length === 0 && (
                  <tr>
                    <td
                      colSpan={6}
                      className="py-8 text-center text-muted-foreground"
                    >
                      未找到符合条件的作业票。
                    </td>
                  </tr>
                )}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>
      
      <AlertDialog open={!!showVoidAlert} onOpenChange={(open) => !open && setShowVoidAlert(null)}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>确认作废操作票？</AlertDialogTitle>
            <AlertDialogDescription>
              此操作不可撤销。作废后，该操作票将无法执行或编辑。
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>取消</AlertDialogCancel>
            <AlertDialogAction onClick={() => showVoidAlert && handleVoidTicket(showVoidAlert)}>
              确认作废
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  )
} 